package LunaServer.gui;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.LocalDateTime;

import LunaServer.core.LunaServer;
import LunaServer.config.ConfigManager;
import LunaServer.logging.*;

/**
 * 服务器管理图形界面类
 * 用于管理路由行为、数据库行为、用户可用字段、数据库地址等信息
 */
public class ServerManagerGUI extends JFrame {
    private LunaServer server;
    private int port;
    private ConfigManager configManager;

    // GUI组件
    private JTextField portField;
    private JTextArea logArea;
    private JTable routesTable;
    private DefaultTableModel routesTableModel;
    private JTextField dbUrlField;
    private JTextField dbUserField;
    private JPasswordField dbPassField;
    private JTextField newRoutePathField;
    private JTextField newRouteFilePathField;
    private JList<String> routeClasspathList;
    private DefaultListModel<String> routeClasspathModel;
    private JTextField newClasspathEntryField;
    private JButton addClasspathButton;
    private JButton removeClasspathButton;
    private JButton startButton;
    private JButton stopButton;
    private JButton addRouteButton;
    private JButton removeRouteButton;
    private JButton reloadRoutesButton;
    private JButton browseFileButton;
    private JLabel statusLabel;
    private JLabel dbStatusLabel;

    // 数据存储
    private Map<String, String> routesMap = new HashMap<>();
    private Map<String, String> fileRoutesMap = new HashMap<>();
    private String dbUrl;
    private String dbUser;
    private String dbPass;

    // 标记服务器是否正在运行
    private boolean serverRunning = false;

    // 获得Logger，暂时不注册。
    private Logger logger = null;

    // 并实例化一个本例的监听器。
    private Listener loggerListener = null;

    public ServerManagerGUI() {
        // 注册到全局 Logger（如果存在）以接收日志通知
        try {
            logger = Logger.getInstance();
            loggerListener = new Listener(this);
            // 然后注册
            logger.addListener(loggerListener);
        } catch (Exception ignore) {
            // 如果 Logger 不可用，忽略
        }

        configManager = new ConfigManager();
        // 从配置文件加载默认配置
        String portStr = configManager.getServerProperty("server.port", "6003");
        port = Integer.parseInt(portStr);
        dbUrl = configManager.getProperty("database.url", "jdbc:postgresql://127.0.0.1:5432/postgres");
        dbUser = configManager.getProperty("database.user", "postgres");
        dbPass = configManager.getProperty("database.password", "lunamoon");

        initializeComponents();
        setupLayout();
        setupEventHandlers();
        loadDefaultRoutes(); // 在初始化时加载默认路由和配置文件中的路由
        loadRouteDependencies(); // 加载路由依赖配置
        // 移除重复的事件处理器设置
        // setupEventHandlersWithButtons(testDbButton, clearLogButton, exportLogButton);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("LunaServer 管理面板");
        setSize(1200, 650); // 增加窗口宽度
        setLocationRelativeTo(null);
    }

    /**
     * 初始化界面组件
     */
    private void initializeComponents() {
        portField = new JTextField(String.valueOf(port), 10);
        logArea = new JTextArea(10, 50);
        logArea.setEditable(false);
        logArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

        // 路由表格
        String[] columnNames = { "路径", "处理器", "类型" };
        routesTableModel = new DefaultTableModel(columnNames, 0) {
            // 设置表格为不可编辑
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        routesTable = new JTable(routesTableModel);

        // 数据库设置组件
        dbUrlField = new JTextField(dbUrl, 50);
        dbUserField = new JTextField(dbUser, 50);
        dbPassField = new JPasswordField(dbPass, 50);
        dbStatusLabel = new JLabel("数据库状态: 等待启动");

        // 新路由组件
        newRoutePathField = new JTextField(20);
        newRouteFilePathField = new JTextField(20);
        browseFileButton = new JButton("浏览...");

        // 路由依赖设置组件
        routeClasspathModel = new DefaultListModel<>();
        routeClasspathList = new JList<>(routeClasspathModel);
        routeClasspathList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        routeClasspathList.setVisibleRowCount(4);
        newClasspathEntryField = new JTextField(30);
        addClasspathButton = new JButton("添加");
        removeClasspathButton = new JButton("删除");

        // 按钮组件
        startButton = new JButton("启动服务器");
        stopButton = new JButton("停止服务器");
        addRouteButton = new JButton("添加路由");
        removeRouteButton = new JButton("删除路由"); // 新增的删除路由按钮
        reloadRoutesButton = new JButton("重载路由"); // 新增的重载路由按钮

        // 状态标签
        statusLabel = new JLabel("服务器未运行");
    }

    /**
     * 设置布局
     */
    private void setupLayout() {
        setLayout(new BorderLayout());

        // 顶部面板 - 服务器控制
        JPanel topPanel = new JPanel(new FlowLayout());
        topPanel.setBorder(BorderFactory.createTitledBorder("服务器控制"));
        topPanel.add(new JLabel("端口: "));
        topPanel.add(portField);
        topPanel.add(startButton);
        topPanel.add(stopButton);
        topPanel.add(dbStatusLabel);
        add(topPanel, BorderLayout.NORTH);

        // 中间面板 - 分割窗格
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);

        // 左侧面板 - 路由和数据库设置
        JPanel leftPanel = new JPanel(new BorderLayout());

        // 路由面板
        JPanel routesPanel = new JPanel(new BorderLayout());
        routesPanel.setBorder(BorderFactory.createTitledBorder("路由管理"));
        routesPanel.add(new JScrollPane(routesTable), BorderLayout.CENTER);

        // 添加新路由面板
        JPanel addRoutePanel = new JPanel(new BorderLayout());
        addRoutePanel.setBorder(BorderFactory.createTitledBorder("添加新路由"));

        // 路由输入面板
        JPanel routeInputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(2, 2, 2, 2);

        // 路径输入
        gbc.gridx = 0;
        gbc.gridy = 0;
        routeInputPanel.add(new JLabel("路径:"), gbc);
        gbc.gridx = 1;
        gbc.weightx = 1.0;
        routeInputPanel.add(newRoutePathField, gbc);

        // 文件路径输入
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.0;
        routeInputPanel.add(new JLabel("文件路径:"), gbc);
        gbc.gridx = 1;
        gbc.weightx = 1.0;
        routeInputPanel.add(newRouteFilePathField, gbc);
        gbc.gridx = 2;
        gbc.weightx = 0.0;
        routeInputPanel.add(browseFileButton, gbc);

        addRoutePanel.add(routeInputPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(addRouteButton);
        buttonPanel.add(removeRouteButton); // 添加删除路由按钮
        buttonPanel.add(reloadRoutesButton); // 添加重载路由按钮
        addRoutePanel.add(buttonPanel, BorderLayout.SOUTH);

        routesPanel.add(addRoutePanel, BorderLayout.SOUTH);

        leftPanel.add(routesPanel, BorderLayout.CENTER);

        // 数据库设置面板
        JPanel dbPanel = new JPanel();
        dbPanel.setLayout(new BoxLayout(dbPanel, BoxLayout.Y_AXIS));
        dbPanel.setBorder(BorderFactory.createTitledBorder("数据库设置"));

        // URL行
        JPanel urlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 2));
        JLabel urlLabel = new JLabel("URL:");
        urlLabel.setPreferredSize(new Dimension(60, 22)); // 统一标签宽度
        urlPanel.add(urlLabel);
        dbUrlField.setPreferredSize(new Dimension(250, 22)); // 增加输入框长度
        urlPanel.add(dbUrlField);

        // 用户名行
        JPanel userPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 2));
        JLabel userLabel = new JLabel("用户名:");
        userLabel.setPreferredSize(new Dimension(60, 22)); // 统一标签宽度
        userPanel.add(userLabel);
        dbUserField.setPreferredSize(new Dimension(250, 22)); // 增加输入框长度
        userPanel.add(dbUserField);

        // 密码行
        JPanel passPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 2));
        JLabel passLabel = new JLabel("密码:");
        passLabel.setPreferredSize(new Dimension(60, 22)); // 统一标签宽度
        passPanel.add(passLabel);
        dbPassField.setPreferredSize(new Dimension(250, 22)); // 增加输入框长度
        passPanel.add(dbPassField);

        // 按钮行
        JPanel buttonPanel2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 2));
        JButton testDbButton = new JButton("测试连接");
        testDbButton.setPreferredSize(new Dimension(80, 22));
        JButton clearLogButton = new JButton("清理日志");
        clearLogButton.setPreferredSize(new Dimension(80, 22));
        JButton exportLogButton = new JButton("导出日志");
        exportLogButton.setPreferredSize(new Dimension(80, 22));
        buttonPanel2.add(testDbButton);
        buttonPanel2.add(clearLogButton);
        buttonPanel2.add(exportLogButton);

        dbPanel.add(urlPanel);
        dbPanel.add(userPanel);
        dbPanel.add(passPanel);
        dbPanel.add(buttonPanel2);

        // 路由依赖设置面板
        JPanel routeDepPanel = new JPanel();
        routeDepPanel.setLayout(new BoxLayout(routeDepPanel, BoxLayout.Y_AXIS));
        routeDepPanel.setBorder(BorderFactory.createTitledBorder("路由依赖设置"));

        // Classpath列表
        JPanel classpathListPanel = new JPanel(new BorderLayout());
        classpathListPanel.add(new JLabel("Classpath条目:"), BorderLayout.NORTH);
        classpathListPanel.add(new JScrollPane(routeClasspathList), BorderLayout.CENTER);
        routeDepPanel.add(classpathListPanel);

        // 添加和删除按钮面板
        JPanel classpathButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        classpathButtonPanel.add(new JLabel("新增条目:"));
        classpathButtonPanel.add(newClasspathEntryField);

        // 添加浏览按钮
        JButton browseClasspathButton = new JButton("浏览...");
        classpathButtonPanel.add(browseClasspathButton);

        classpathButtonPanel.add(addClasspathButton);
        classpathButtonPanel.add(removeClasspathButton);
        routeDepPanel.add(classpathButtonPanel);

        // 保存按钮
        JPanel saveButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton saveDepButton = new JButton("保存依赖配置");
        saveButtonPanel.add(saveDepButton);
        routeDepPanel.add(saveButtonPanel);

        // 添加事件监听器
        addClasspathButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newEntry = newClasspathEntryField.getText().trim();
                if (!newEntry.isEmpty()) {
                    routeClasspathModel.addElement(newEntry);
                    newClasspathEntryField.setText("");
                }
            }
        });

        // 添加浏览按钮事件监听器
        browseClasspathButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                fileChooser.setMultiSelectionEnabled(true);

                // 设置文件过滤器
                fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                    @Override
                    public boolean accept(File f) {
                        return f.isDirectory() || f.getName().endsWith(".jar");
                    }

                    @Override
                    public String getDescription() {
                        return "JAR文件和目录";
                    }
                });

                int result = fileChooser.showOpenDialog(ServerManagerGUI.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File[] selectedFiles = fileChooser.getSelectedFiles();
                    for (File file : selectedFiles) {
                        String path = file.getAbsolutePath();
                        // 如果是Windows系统，将路径分隔符转换为正斜杠
                        if (System.getProperty("os.name").toLowerCase().contains("win")) {
                            path = path.replace("\\", "/");
                        }
                        routeClasspathModel.addElement(path);
                    }
                }
            }
        });

        removeClasspathButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedIndex = routeClasspathList.getSelectedIndex();
                if (selectedIndex != -1) {
                    routeClasspathModel.remove(selectedIndex);
                } else {
                    JOptionPane.showMessageDialog(ServerManagerGUI.this,
                            "请先选择要删除的条目", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });

        saveDepButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (configManager != null) {
                    java.util.List<String> classpathList = new java.util.ArrayList<>();
                    for (int i = 0; i < routeClasspathModel.getSize(); i++) {
                        classpathList.add(routeClasspathModel.getElementAt(i));
                    }
                    configManager.setRouteDependencyList("classpath", classpathList);
                    logger.info("路由依赖设置已保存，共 " + classpathList.size() + " 个条目");
                }
            }
        });

        leftPanel.add(routesPanel, BorderLayout.CENTER);
        leftPanel.add(dbPanel, BorderLayout.SOUTH);
        leftPanel.add(routeDepPanel, BorderLayout.NORTH);

        // 右侧面板 - 日志区域
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.setBorder(BorderFactory.createTitledBorder("日志"));
        rightPanel.add(new JScrollPane(logArea), BorderLayout.CENTER);

        splitPane.setLeftComponent(leftPanel);
        splitPane.setRightComponent(rightPanel);
        splitPane.setDividerLocation(500); // 增加左侧面板宽度，从而增加右侧面板（日志区域）的宽度

        add(splitPane, BorderLayout.CENTER);

        // 底部面板 - 状态栏
        JPanel bottomPanel = new JPanel(new FlowLayout());
        bottomPanel.add(new JLabel("状态: "));
        bottomPanel.add(statusLabel);
        bottomPanel.add(Box.createHorizontalStrut(20)); // 添加一些间距
        bottomPanel.add(new JLabel("数据库: "));
        bottomPanel.add(dbStatusLabel);
        add(bottomPanel, BorderLayout.SOUTH);

        // 设置事件处理器
        setupEventHandlersWithButtons(testDbButton, clearLogButton, exportLogButton);
    }

    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        // 启动服务器按钮事件
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startServer();
            }
        });

        // 停止服务器按钮事件
        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                stopServer();
            }
        });

        // 添加路由按钮事件
        addRouteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addNewRoute();
            }
        });

        // 删除路由按钮事件
        removeRouteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                removeSelectedRoute();
            }
        });

        // 重载路由按钮事件
        reloadRoutesButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                reloadRoutes();
            }
        });

        // 浏览文件按钮事件
        browseFileButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                browseForFile();
            }
        });

        // 移除输入框的回车事件监听器，避免重复执行操作
        // dbUrlField.addActionListener(...);
        // dbUserField.addActionListener(...);
        // dbPassField.addActionListener(...);
        // dbPassField.addActionListener(...);
    }

    /**
     * 设置事件处理器（带按钮）
     * 修复重复注册事件监听器的问题
     */
    private void setupEventHandlersWithButtons(JButton testDbButton, JButton clearLogButton, JButton exportLogButton) {
        // 测试数据库连接按钮
        testDbButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                testDatabaseConnection();
            }
        });

        // 清理日志按钮
        clearLogButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clearLog();
            }
        });

        // 导出日志按钮
        exportLogButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                exportLog();
            }
        });
    }

    /**
     * 浏览文件
     */
    private void browseForFile() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter("Java Files", "java"));
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            newRouteFilePathField.setText(fileChooser.getSelectedFile().getAbsolutePath());
        }
    }

    /**
     * 测试数据库连接
     * - 该函数会创建一个新的连接，并关闭该连接。TODO: 在正式开服时必须使用连接池。
     */
    private void testDatabaseConnection() {
        String url = dbUrlField.getText();
        String user = dbUserField.getText();
        String pass = new String(dbPassField.getPassword());

        dbStatusLabel.setText("数据库状态: 测试中...");
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    Connection connection = DriverManager.getConnection(url, user, pass);
                    boolean isValid = connection.isValid(5); // 5秒超时
                    connection.close();

                    if (isValid) {
                        dbStatusLabel.setText("数据库状态: 连接成功");
                        dbStatusLabel.setForeground(Color.GREEN);
                        logger.info("数据库连接测试成功");
                    } else {
                        dbStatusLabel.setText("数据库状态: 连接失败");
                        dbStatusLabel.setForeground(Color.RED);
                        logger.warn("数据库连接测试失败");
                    }
                } catch (SQLException e) {
                    dbStatusLabel.setText("数据库状态: 连接错误");
                    dbStatusLabel.setForeground(Color.RED);
                    logger.error("数据库连接错误: " + e.getMessage());
                }
            }
        });
    }

    /**
     * 加载默认路由
     */
    private void loadDefaultRoutes() {
        // 从配置文件加载路由
        if (configManager != null) {
            Map<String, String> savedRoutes = configManager.getRoutes();
            fileRoutesMap.putAll(savedRoutes);

            for (Map.Entry<String, String> entry : savedRoutes.entrySet()) {
                routesTableModel.addRow(new Object[] { entry.getKey(), entry.getValue(), "Java文件" });
            }

            if (!savedRoutes.isEmpty()) {
                logger.info("从配置文件加载了 " + savedRoutes.size() + " 个路由");
            }
        }
    }

    /**
     * 加载路由依赖配置
     */
    private void loadRouteDependencies() {
        if (configManager != null) {
            java.util.List<String> classpathList = configManager.getRouteDependencyList("classpath",
                    java.util.Arrays.asList("src", "lib/gson-gson-parent-2.13.2/gson/target/classes",
                            "lib/gson-gson-parent-2.13.2/gson/lib/*", "."));

            routeClasspathModel.clear();
            for (String entry : classpathList) {
                routeClasspathModel.addElement(entry);
            }

            logger.info("路由依赖配置已加载，共 " + classpathList.size() + " 个条目");
        }
    }

    /**
     * 启动服务器
     */
    private void startServer() {
        // 检查服务器是否已经在运行
        if (serverRunning) {
            JOptionPane.showMessageDialog(this, "服务器已在运行中，请勿重复启动", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }

        try {
            port = Integer.parseInt(portField.getText());
            server = new LunaServer();

            // 设置数据库配置
            server.setDatabaseConfig(dbUrlField.getText(), dbUserField.getText(),
                    new String(dbPassField.getPassword()));

            // 注册文件路由（包括从配置文件加载的路由）
            for (Map.Entry<String, String> entry : fileRoutesMap.entrySet()) {
                server.addFileRoute(entry.getKey(), entry.getValue());
            }

            // 实际启动服务器
            server.startServer(port);

            // 测试数据库连接
            testDatabaseConnection();

            logger.info("服务器正在端口 " + port + " 上启动...");
            logger.info("注册的路由:");
            for (Map.Entry<String, String> entry : routesMap.entrySet()) {
                logger.info("  " + entry.getKey() + " -> " + entry.getValue() + " (内置)");
            }
            for (Map.Entry<String, String> entry : fileRoutesMap.entrySet()) {
                logger.info("  " + entry.getKey() + " -> " + entry.getValue() + " (Java文件路由)");
            }
            logger.info("数据库设置:");
            logger.info("URL: " + dbUrlField.getText());
            logger.info("用户: " + dbUserField.getText());
            logger.info("服务器启动成功!");

            // 更新状态栏
            statusLabel.setText("服务器运行中 - 端口: " + port);
            serverRunning = true;

            // 保存当前配置到文件
            configManager.setProperty("server.port", String.valueOf(port));
            configManager.setProperty("database.url", dbUrlField.getText());
            configManager.setProperty("database.user", dbUserField.getText());
            configManager.setProperty("database.password", new String(dbPassField.getPassword()));

        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "端口号必须是一个有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
        } catch (Exception e) {
            logger.error("启动服务器时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 停止服务器
     */
    private void stopServer() {
        if (!serverRunning) {
            JOptionPane.showMessageDialog(this, "服务器未在运行", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        if (server != null) {
            server.stopServer();
            logger.info("服务器已停止");
            server = null;

            // 更新状态栏
            statusLabel.setText("服务器未运行");
            serverRunning = false;

            // 重置数据库状态
            resetDatabaseStatus();
            // 从全局 Logger 注销监听器（防止内存泄漏）
            try {
                if (loggerListener != null) {
                    Logger logger = Logger.getInstance();
                    logger.removeListener(loggerListener);
                    loggerListener = null;
                }
            } catch (Exception ignore) {
            }
        }
    }

    /**
     * 重置数据库状态
     */
    private void resetDatabaseStatus() {
        dbStatusLabel.setText("数据库状态: 未知");
        dbStatusLabel.setForeground(Color.BLACK);
    }

    /**
     * 添加新路由
     */
    private void addNewRoute() {
        String path = newRoutePathField.getText().trim();
        String filePath = newRouteFilePathField.getText().trim();

        if (path.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请提供路由路径", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (filePath.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请提供Java文件路径", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 添加到数据模型
        fileRoutesMap.put(path, filePath);
        routesTableModel.addRow(new Object[] { path, filePath, "Java文件" });
        logger.info("添加Java文件路由: " + path + " -> " + filePath);

        // 保存到配置文件
        if (configManager != null) {
            configManager.addRoute(path, filePath);
            logger.info("路由配置已保存到配置文件");
        }

        // 清空输入框
        newRoutePathField.setText("");
        newRouteFilePathField.setText("");
    }

    /**
     * 删除选中的路由
     */
    private void removeSelectedRoute() {
        int selectedRow = routesTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的路由", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        // 获取选中行的数据
        String path = (String) routesTableModel.getValueAt(selectedRow, 0);
        String type = (String) routesTableModel.getValueAt(selectedRow, 2);

        // 检查是否为内置路由
        if ("内置".equals(type)) {
            JOptionPane.showMessageDialog(this, "无法删除内置路由: " + path, "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 确认删除
        int result = JOptionPane.showConfirmDialog(this,
                "确定要删除路由 " + path + " 吗？",
                "确认删除",
                JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {
            // 从数据模型中移除
            routesTableModel.removeRow(selectedRow);
            fileRoutesMap.remove(path);

            // 从配置文件中移除
            if (configManager != null) {
                configManager.removeRoute(path);
                logger.info("路由配置已从配置文件中移除");
            }

            // 如果服务器正在运行，也需要从服务器中移除
            if (serverRunning && server != null) {
                boolean removed = server.removeContext(path);
                if (removed) {
                    logger.info("路由已从服务器中删除: " + path);
                } else {
                    logger.error("无法从服务器中删除路由: " + path);
                }
            }

            logger.info("删除路由: " + path);
        }
    }

    /**
     * 重载路由
     */
    private void reloadRoutes() {
        if (!serverRunning || server == null) {
            JOptionPane.showMessageDialog(this, "服务器未在运行，无法重载路由", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int result = JOptionPane.showConfirmDialog(this,
                "确定要重载路由配置吗？这将清除当前所有自定义路由并重新加载。",
                "确认重载路由",
                JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {
            try {
                // 调用服务器的重载路由方法
                server.reloadRoutes(fileRoutesMap);
                logger.info("路由配置已重载");
                JOptionPane.showMessageDialog(this, "路由配置重载成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                logger.error("重载路由时出错: " + e.getMessage());
                JOptionPane.showMessageDialog(this, "重载路由失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * 往log区写入消息，自动换行。
     * 
     * @param message 要被写入的文本内容。
     */
    private void logMessage(String message) {
        logArea.append(message + "\n");
        logArea.setCaretPosition(logArea.getDocument().getLength());
    }

    /**
     * 一个用于处理接口的公共函数。调用约定：只能实现
     * 
     * @param level     log级别
     * @param message   文本
     * @param timestamp 时间戳
     */
    public void log(LogLevel level, String message, LocalDateTime timestamp) {
        logMessage(timestamp + " [" + level + "] " + message);
    }

    /**
     * 清理日志
     */
    private void clearLog() {
        logArea.setText("");
        logger.info("日志已清理");
    }

    /**
     * 导出日志
     */
    private void exportLog() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择导出日志文件的位置");
        fileChooser.setSelectedFile(new java.io.File("server_log.txt"));

        int userSelection = fileChooser.showSaveDialog(this);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            java.io.File fileToSave = fileChooser.getSelectedFile();
            try {
                java.io.FileWriter writer = new java.io.FileWriter(fileToSave);
                writer.write(logArea.getText());
                writer.close();
                logger.info("日志已导出到: " + fileToSave.getAbsolutePath());
                JOptionPane.showMessageDialog(this, "日志导出成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (java.io.IOException e) {
                logger.info("导出日志失败: " + e.getMessage());
                JOptionPane.showMessageDialog(this, "导出日志失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * 获取数据库URL
     */
    public String getDbUrl() {
        return dbUrlField.getText();
    }

    /**
     * 获取数据库用户名
     */
    public String getDbUser() {
        return dbUserField.getText();
    }

    /**
     * 获取数据库密码
     */
    public String getDbPass() {
        return new String(dbPassField.getPassword());
    }

    /**
     * 获取所有路由
     */
    public Map<String, String> getRoutes() {
        return new HashMap<>(routesMap);
    }

    /**
     * 获取所有文件路由
     */
    public Map<String, String> getFileRoutes() {
        return new HashMap<>(fileRoutesMap);
    }
}

class Listener implements LogListener {

    private ServerManagerGUI guiInstance = null;

    // 必须传入一个本实例。
    public Listener(ServerManagerGUI guiInstance) {
        this.guiInstance = guiInstance;
    }

    @Override
    public void onLog(LogLevel level, String message, LocalDateTime timestamp) {
        // 在这个监听器启动时，使用私有类对log处理。
        this.guiInstance.log(level, message, timestamp);
    };
}
